package com.feilong.edgeAI.service;

import static com.feilong.edgeAI.service.FeiLongService.feilongRespone;
import static com.feilong.edgeAI.service.FeiLongService.hasConnect;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.accessibilityservice.GestureDescription;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Notification;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Path;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.os.RemoteException;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityNodeInfo;

import androidx.annotation.RequiresApi;

import com.feilong.edgeAI.R;
import com.feilong.edgeAI.autosendwechatmsg.WeChatTextWrapper;
import com.feilong.edgeAI.autosendwechatmsg.WechatUtils;
import com.feilong.edgeAI.model.CurrentUI;
import com.feilong.edgeAI.model.GlobalEvent;
import com.feilong.edgeAI.model.NoticeMsg;
import com.feilong.edgeAI.model.TtsMsg;
import com.feilong.edgeAI.model.WechatHome;
import com.feilong.edgeAI.model.WechatHomeFinish;
import com.feilong.edgeAI.model.WeixinMsg;
import com.feilong.edgeAI.utils.AppUtils;
import com.feilong.edgeAI.utils.TextUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AewmeService extends AccessibilityService {
    public static final String TAG = "AewmeService";

    private AccessibilityManager mAccessibilityManager;
    private Context mContext;
    private static AewmeService mInstance;
    public static final String TERMUX_PKG = "com.termux";
    public static final String EXAGEAR_PKG = "com.eltechs.ed";
    public static final String WX_PKG = "com.tencent.mm";
    public static final String MMS_PKG = "com.android.mms";
    public static final String TAOBAO_PKG = "com.taobao.taobao";
    public static final String GrantPermissionsActivity = "com.android.permissioncontroller.permission.ui.GrantPermissionsActivity";
    private Map<String, String> notications = new HashMap<>();
    private int screenWidth;
    private int screenHeight;
    private long lastCreateTime;
    private List<String> allNameList = new ArrayList<>();
    private int mRepeatCount;

    public static boolean hasSend;
    public static boolean OPEN_EXAGEAR;
    public static final int SEND_FAIL = 0;
    public static final int SEND_SUCCESS = 1;
    public static int SEND_STATUS;

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void init(Context context) {
        mContext = context.getApplicationContext();
        mAccessibilityManager = (AccessibilityManager) mContext.getSystemService(Context.ACCESSIBILITY_SERVICE);
//        SoftKeyboardController softController = getSoftKeyboardController();
//        softController.addOnShowModeChangedListener(new SoftKeyboardController.OnShowModeChangedListener() {
//            @Override
//            public void onShowModeChanged(@NonNull SoftKeyboardController controller, int showMode) {
//                Log.e(TAG, "onShowModeChanged: showMode="+showMode);
//            }
//        });
    }

    @Override
    public void onCreate() {
        super.onCreate();
        notications.put(WX_PKG, "微信");
        notications.put(MMS_PKG, "短信");
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        EventBus.getDefault().post(this);
        return super.onStartCommand(intent, flags, startId);
    }

    public static AewmeService getInstance() {
        if (mInstance == null) {
            mInstance = new AewmeService();
        }
        return mInstance;
    }

    private OnNotifyTextReciveListener onNotifyTextReciveListener;

    public interface OnNotifyTextReciveListener {
        void onNotifyTextRecive(String text);
    }

    public void setOnNotifyTextReciveListener(OnNotifyTextReciveListener onNotifyTextReciveListener) {
        this.onNotifyTextReciveListener = onNotifyTextReciveListener;
    }

    private AccessibilityNodeInfo rootNode;
    private AccessibilityNodeInfo wxmsgEditText;
    private AccessibilityNodeInfo searchFriendEditText;
    private AccessibilityNodeInfo searchBtn;
    private AccessibilityNodeInfo sendMsgBtn;
    private AccessibilityNodeInfo selectFriend;
    private AccessibilityNodeInfo moneyNode;
    private AccessibilityNodeInfo sendRedPackNode;
    private String wxClassName = "";
    public static String currentPackageName = "";
    public static String contentPackageName = "";
    public static String anyPackageName = "";
    public static String currentActivity = "";
    private String targetActivity = "";
    private AccessibilityEvent lastEvent;
    private List<AccessibilityNodeInfo> allNodes = new ArrayList<>();
    private Map<String, AccessibilityNodeInfo> maps = new HashMap<>();

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        // 获取事件源
        AccessibilityNodeInfo source = event.getSource();
        String activityName="";
        String pkgname = " ";
        if (source != null) {
            pkgname = source.getPackageName().toString();
            if (pkgname.contains("launcher")) {
                handler.removeMessages(CLICK_BACK_SERIES);
                if (WeChatTextWrapper.WechatClass.WECHAT_CLASS_LAUNCHUI.equals(targetActivity)) {
                    EventBus.getDefault().post(new WechatHomeFinish());
                }
            }
            if (event.getEventType() == event.TYPE_WINDOW_STATE_CHANGED) {

                //获取当前窗口activity名
                ComponentName componentName = new ComponentName(
                        event.getPackageName().toString(),
                        event.getClassName().toString()
                );
                try {
                    activityName = getPackageManager().getActivityInfo(componentName, 0).toString();
                    currentActivity = activityName.substring(activityName.indexOf(" ") + 1, activityName.indexOf("}"));
                } catch (Exception e) {
                    Log.d(TAG, "onAccessibilityEvent: " + e.getMessage());
                    e.printStackTrace();
                    return;
                }
            }
        }
        anyPackageName = pkgname;
        lastEvent = event;
        Log.d(TAG, "onAccessibilityEvent:event. " + event.toString());
        Log.d(TAG, "onAccessibilityEvent:currentActivity=" + currentActivity);
        Log.d(TAG, "onAccessibilityEvent:activityName=" + activityName);
        Log.e(TAG, "onAccessibilityEvent:pkgname=" + pkgname);
        targets.clear();
        maps.clear();
        if (null != event.getSource()) {
            rootNode = event.getSource();
        }

//        Log.d(TAG, "onAccessibilityEvent: getPackageName=" + currentPackageName);

        Log.d(TAG, "onAccessibilityEvent: type=" + weixinType);
        switch (event.getEventType()) {
            //通知栏变化时,处理微信和短信提示
            case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:
                Log.d(TAG, "onAccessibilityEvent: event.getPackageName()=" + event.getPackageName());
                if (event.getPackageName().equals(WX_PKG) || event.getPackageName().equals(MMS_PKG)) {
                    setNotications(event);
                }

                break;
            case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                Log.e(TAG, "onAccessibilityEvent: pkgname=" + pkgname);
                if (rootNode == null) {
                    return;
                }
                if (!TextUtils.isEmpty(pkgname)) {
                    currentPackageName = pkgname;
                    Log.e(TAG, "onAccessibilityEvent: currentPackageName=" + currentPackageName);
                }
                Log.d(TAG, "onAccessibilityEvent: currentActivity=" + currentActivity);
                if (currentPackageName.equals(EXAGEAR_PKG)) {
                    if (event.getClassName().toString().equals("android.app.Dialog")) {
                        traverseNodeByText(rootNode, allNodes, "DEFAULT CONTROLS");
                        if (targets.size() > 0) {
                            handler.sendEmptyMessageDelayed(CLOSE_TIP, 300);
                        }
                    }
                    //exagear启动exe界面
                    if (event.getClassName().toString().equals("com.eltechs.axs.activities.XServerDisplayActivity")) {
                        traverseNodeByClass(rootNode, allNodes, "android.widget.ImageButton");
                        //语音助手启动exagear时已经是XServerDisplayActivity界面，没有连接成功就重启一次
                        if (System.currentTimeMillis() - exagearActionTime < 2000) {
                            if (targets.size() > 0) {
                                AccessibilityNodeInfo info = targets.get(targets.size() - 1);
                                info.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            }
                        } else {
                            //双击text.ext
                            if (!hasConnect) {
                                handler.sendEmptyMessageDelayed(CLOSE_TIP, 300);
                                handler.sendEmptyMessageDelayed(CLICK_EXE, 6000);
                                handler.sendEmptyMessageDelayed(CLICK_EXE, 6080);
                                handler.sendEmptyMessageDelayed(GO_HOME, 6600);
                            }
                        }
                    } else if ("com.eltechs.ed.activities.EDMainActivity".equals(currentActivity)) {
                        exeFileIsStarted = false;
                        traverseNodeByClass(rootNode, allNodes, "android.widget.ImageButton");
                        Log.d(TAG, "onAccessibilityEvent: targets=" + targets.size());
                        if (targets.size() > 1) {//已经创建了模拟环境的容器
                            AccessibilityNodeInfo info = targets.get(targets.size() - 1);
                            info.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    tap(630, 330);
//                                    tap(630, 450);
                                }
                            }, 300);
                        } else {//点击创建模拟环境的容器
//                                clickTextViewByID("manage_containers_new");
                            if (System.currentTimeMillis() - lastCreateTime > 5000) {
//                                createContainer();
                                click(0.943, 0.073, "createContainer");
                            }
                            lastCreateTime = System.currentTimeMillis();
                        }
//                        clickItemByText(rootNode, allNodes, "启动");
                    } else if (currentActivity.equals("com.eltechs.ed.activities.EDStartupActivity")) {
                        exeFileIsStarted = false;
                        traverseNodeByClass(rootNode, allNodes, "android.widget.ImageButton");
                        Log.d(TAG, "onAccessibilityEvent: targets=" + targets.size());
                        if (targets.size() > 1) {//已经创建了模拟环境的容器
                            AccessibilityNodeInfo info = targets.get(targets.size() - 1);
                            info.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        } else {//点击创建模拟环境的容器
//                                clickTextViewByID("manage_containers_new");
                            if (System.currentTimeMillis() - lastCreateTime > 5000) {
//                                createContainer();
                                click(0.943, 0.073, "createContainer");
                            }
                            lastCreateTime = System.currentTimeMillis();
                        }
                        clickItemByText(rootNode, allNodes, "启动");
                    }
                    if (hasConnect) {
                        Log.d(TAG, "onAccessibilityEvent: hasConnect=" + hasConnect);
                        return;
                    }
                    if (clickTextViewByText("允许")) {
                        Log.d(TAG, "onAccessibilityEvent: 允许");
                        return;
                    }
                    if (clickTextViewByText("ok")) {
                        Log.d(TAG, "onAccessibilityEvent: ok");
                        return;
                    }
                        /*List<AccessibilityNodeInfo> launchNodes = rootNode.findAccessibilityNodeInfosByText("克隆");
                        if (launchNodes.size() > 0) {
                            click(0.85,0.19,"启动");
//                        handler.sendEmptyMessageDelayed(0,9000);
                            return;
                        }*/

                } else if (currentPackageName.endsWith(".permissioncontroller")) {
                    traverseNodeByText(rootNode, allNodes, "ExaGear ED302");
                    Log.d(TAG, "onAccessibilityEvent ExaGear:targets.size=" + targets.size());
                    if (targets.size() > 0) {
                        allowNodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }
                } else if (currentPackageName.endsWith(".permissioncontroller")) {
                    traverseNodeByText(rootNode, allNodes, "ExaGear ED302");
                    Log.d(TAG, "onAccessibilityEvent ExaGear:targets.size=" + targets.size());
                    if (targets.size() > 0) {
                        allowNodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }
                } else if ("com.taobao.search.searchdoor.SearchDoorActivity".endsWith(currentActivity)) {
                    traverseTaoBaoNode(rootNode, allNodes, "");
                    if (null != taobaoSearchBtn) {
                        taobaoSearchBtn.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        taobaoSearchBtn.refresh();
                        feilongRespone.setIntent("");
                    }
                } else if ("com.freeme.camera".equals(currentPackageName) && "拍照".equals(FeiLongService.feilongRespone.getTarget())) {
                    traverseCameraNode(rootNode, allNodes, "camera");
                    if (meiyanNodeInfo != null && takePhotoNodeInfo != null) {
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                tap(360, 1360);
                                meiyanNodeInfo = null;
                                takePhotoNodeInfo = null;
                            }
                        }, 3000);
                    }
                } else if (WX_PKG.equals(currentPackageName)) {
                    wxClassName = currentActivity;
                    Log.e(TAG, "onAccessibilityEvent:currentPackageName.equals(WX_PKG  wxClassName=" + wxClassName);
                    Log.d(TAG, "onAccessibilityEvent:weixinType= " + weixinType);
                    if (!weixinHandle) {
                        return;
                    }
                    switch (weixinType) {
                        case WEIXIN_FIND_NAME:
                            Log.d(TAG, "onAccessibilityEvent: currentActivity=" + currentActivity);
                           /* if (currentActivity.equals(WeChatTextWrapper.WechatClass.WECHAT_CLASS_LAUNCHUI) && (System.currentTimeMillis() - weixinActionTime < 3000)) {//在微信主界面找到搜索按钮
                                handleFlow_LaunchUI();
                                traverseNodeByDescription(rootNode, allNodes, false);
                                Log.d(TAG, "WEIXIN_FIND_NAME: targets.size=" + targets.size());
                                if (null != searchBtn) {
                                    Log.d(TAG, "searchBtn: text=" + searchBtn.getText() + "  classname=" + searchBtn.getClassName().toString() + "  id=" + searchBtn.getViewIdResourceName() + "  des=" + searchBtn.getContentDescription());
                                    searchBtn.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                                    lastUserName = WechatUtils.FRIEND_NAME;
                                }
                            } else */
                            if (currentActivity.equals(WeChatTextWrapper.WechatClass.WECHAT_CLASS_MAINSEARCH)) {//输入名字进行搜索
//                                traverseNodeByDescription(rootNode, allNodes, false);
                                WechatUtils.FRIEND_NAME = feilongRespone.getTarget1();
                                intputTargetName(rootNode, allNodes, feilongRespone.getTarget1());
                                Log.d(TAG, "onAccessibilityEvent:traverseNodeByText searchEditText=" + searchFriendEditText + "  FRIEND_NAME=" + WechatUtils.FRIEND_NAME);
                                if (searchFriendEditText != null) {
//                                        setNodeText(searchEditText,WechatUtils.FRIEND_NAME);
                                }
                            } else if (currentActivity.equals(WeChatTextWrapper.WechatClass.WECHAT_CLASS_CHATUI)) {
                                performGlobalAction(GLOBAL_ACTION_BACK);
                            }
                            break;
                        case WEIXIN_MSG:
                            if (currentActivity.equals(WeChatTextWrapper.WechatClass.WECHAT_CLASS_CHATUI)) {
                                Log.e(TAG, "onAccessibilityEvent: WEIXIN_MSG");
                                handler.removeMessages(CLICK_WEIXIN_FRIEND);
                                traverseNodeByDescription(rootNode, allNodes, false);
                                if (!TextUtils.isEmpty(FeiLongService.currentTTS)) {
                                    EventBus.getDefault().post(new CurrentUI());
                                }
                                if (!TextUtils.isEmpty(WechatUtils.MSG_CONTENT)) {

                                    sendWxmsg(WechatUtils.MSG_CONTENT);
                                }
                            }
                            break;
                        case WEIXIN_REDPKG:
                            if (currentActivity.equals(WeChatTextWrapper.WechatClass.WECHAT_CLASS_CHATUI)) {
                                traverseNodeByDescription(rootNode, allNodes, false);
                                if (targets.size() > 0) {
                                    AccessibilityNodeInfo info = targets.get(0);
                                    info.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                                    Log.e(TAG, "com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyPrepareUI");
                                    handler.sendEmptyMessageDelayed(FIND_RED_PACK, 300);
                                    handler.sendEmptyMessageDelayed(FIND_RED_PACK, 400);
                                }
                            } else if (currentActivity.equals(WeChatTextWrapper.WechatClass.WECHAT_CLASS_LUCKYMONEYPREPAREUI)) {
                                traverseRedPackNode(rootNode, allNodes, "");
//                                sendRedPackNode = findViewByText(SEND_REDPACK_TAG,null);
//                                AccessibilityNodeInfo moneyNode = findViewByText(MONEY_TAG,"android.widget.EditText");
                                Log.e(TAG, "onAccessibilityEvent: maps.size()=" + maps.size());
                            }
                            break;
                    }

                }
                break;
            case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED:
                if (rootNode == null) {
                    return;
                }
                if (source != null && source.getPackageName() != null) {
                    contentPackageName = source.getPackageName().toString();
                }
                Log.d(TAG, "onAccessibilityEvent:TYPE_WINDOW_CONTENT_CHANGED= =" + contentPackageName);
                if (null != source && WX_PKG.equals(source.getPackageName())) {
                    if (!weixinHandle) {
                        return;
                    }
//                    if(!currentActivity.startsWith(WX_PKG)){
//                        toWechatFirstUI();
//                        return;
//                    }
                    switch (weixinType) {
                        case WEIXIN_FIND_NAME:
                            wxfriendresearchs.clear();
                            if (WeChatTextWrapper.WechatClass.WECHAT_CLASS_MAINSEARCH.equals(wxClassName)
                            ) {
                                handler.removeMessages(CHECK_SEARCH_RESULT);
                                handler.sendEmptyMessageDelayed(CHECK_SEARCH_RESULT, 1000);
                                Log.e(TAG, "onAccessibilityEvent:TYPE_WINDOW_CONTENT_CHANGED WEIXIN_FIND_NAME=" + event.getClassName().toString());
                            }
                            break;
                        case WEIXIN_MSG:
                            if (wxClassName.equals(WeChatTextWrapper.WechatClass.WECHAT_CLASS_CHATUI)) {
                                Log.e(TAG, "TYPE_WINDOW_CONTENT_CHANGED:WEIXIN_MSG sendMsgBtn " + sendMsgBtn);
                                handler.removeMessages(CLICK_WEIXIN_SEND_MSG);
                                handler.sendEmptyMessageDelayed(CLICK_WEIXIN_SEND_MSG, 1000);
//                                } else {
//                                    clickWxSend();
//                                }
                            }
                            break;
                    }
                    if (WeChatTextWrapper.WechatClass.WECHAT_CLASS_CHATUI.equals(wxClassName)) {
//                        clickTextViewByText("发送");
                    }
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(GlobalEvent event) throws RemoteException {
        Log.d(TAG, "GlobalEvent clickTextViewByText: " + event.getText());
        if (event.getType() != 3) return;
        String action = event.getText();
        if (!TextUtils.isEmpty(action)) {
            if (action.equals("返回")) {
                performGlobalAction(GLOBAL_ACTION_BACK);
            } else {
                clickTextViewByText(event.getText());
            }
        }
    }

    private String lastUserName;

    private void sendWxmsg(String message) {
        Log.d(TAG, "sendWxmsg: " + message);
        if (wxmsgEditText != null && !TextUtils.isEmpty(message)) {
            setNodeText(wxmsgEditText, message);
            WechatUtils.MSG_CONTENT = "";
//                    clickTextViewByText("发送");
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    clickWxSend();
                }
            }, 1000);
        }
    }

    private void clickWxSend() {
        Log.d(TAG, "clickWxSend: sendMsgBtn=" + sendMsgBtn);
        if (sendMsgBtn != null) {
            boolean click = sendMsgBtn.performAction(AccessibilityNodeInfo.ACTION_CLICK);
            Log.e(TAG, "clickWxSend: click=" + click);
            int[] arr = getNodeInfoCoordinate(sendMsgBtn);
            Log.d(TAG, "clickWxSend: arr[0]=" + arr[0]);
            Log.d(TAG, "clickWxSend: arr[1]=" + arr[1]);
//            sendMsgBtn.performAction(AccessibilityNodeInfo.ACTION_CLICK);
            weixinType = -1;
            weixinHandle = false;
            if (click) {
                sendMsgBtn.recycle();
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    Log.e(TAG, "tap: tap=" + arr);
                    tap(arr[0], arr[1]);
                }
            }
        }
    }

    public static boolean exeFileIsStarted;
    public static int weixinType;
    public static final int WEIXIN_FIND_NAME = 1;
    public static final int WEIXIN_MSG = 2;
    public static final int WEIXIN_REDPKG = 3;
    //    private static final String SEARCH_TEXT = "搜索";
//    private static final String SEND_TEXT = "发送";
//    private static final String RED_PACK = "红包";
    public static long weixinActionTime;
    public static long exagearActionTime;

    public void setWeixinType(int type) {
        weixinType = type;
    }

    public static boolean weixinHandle;

    public void setWeightinHandle(boolean handle) {
        weixinHandle = handle;
    }

    private boolean setNodeText(AccessibilityNodeInfo accessibilityNodeInfo, String text) {
        if (null == accessibilityNodeInfo) {
            return false;
        }
        Bundle arguments = new Bundle();
        Log.d(TAG, "setNodeText: text=" + text);
        arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text);
        boolean result = accessibilityNodeInfo.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
        Log.d(TAG, "setNodeText: result= " + result);
        return result;
    }

    private List<AccessibilityNodeInfo> wxfriendresearchs = new ArrayList<>();

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        AccessibilityServiceInfo info = new AccessibilityServiceInfo();
//        info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;
        info.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED | AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED | AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED;
//        info.packageNames = new String[]{EXAGEAR_PKG,WX_PKG};
        info.packageNames = AppUtils.getPackageInfo(this);
        info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
        info.notificationTimeout = 100;
        this.setServiceInfo(info);
        Log.d(TAG, "onServiceConnected: ");
    }

    private List<AccessibilityNodeInfo> targets = new ArrayList<>();

    private void traverseNodeByDescription(AccessibilityNodeInfo node, List<AccessibilityNodeInfo> allNodes, boolean execute) {
        allNodes.add(node);
        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo childNode = node.getChild(i);
            if (null == childNode) {
                continue;
            }
//            if (wxClassName.equals(WeChatTextWrapper.WechatClass.WECHAT_CLASS_CHATUI)) {
//                Log.d(TAG, "traverseNodeByDescription:text " + childNode.getText() + "  classname=" + childNode.getClassName().toString() + "  id=" + childNode.getViewIdResourceName() + "  des=" + childNode.getContentDescription());
//            }
            if (targets.isEmpty()) {
                if (getResources().getString(R.string.search).equals(childNode.getContentDescription()) && "android.widget.RelativeLayout".equals(childNode.getClassName().toString())) {
                    targets.add(childNode);
                    searchBtn = childNode;
                } else if (
//                        SEARCH_TEXT.equals(childNode.getText()) &&
                        wxClassName.equals(WeChatTextWrapper.WechatClass.WECHAT_CLASS_MAINSEARCH) &&
                                "android.widget.EditText".equals(childNode.getClassName())) {
                    if (null == searchFriendEditText) {
                        searchFriendEditText = childNode;
//                        setNodeText(searchEditText,WechatUtils.FRIEND_NAME);
                    }
                    Log.d(TAG, "searchEditText: WechatUtils.FRIEND_NAME=" + WechatUtils.FRIEND_NAME);
                    setNodeText(childNode, WechatUtils.FRIEND_NAME);
                    Log.d(TAG, "traverseNodeByDescription: searchEditText=" + searchFriendEditText + "  \n+FRIEND_NAME=" + WechatUtils.FRIEND_NAME);
                    targets.add(childNode);
                } else if (wxClassName.equals(WeChatTextWrapper.WechatClass.WECHAT_CLASS_CHATUI) && "android.widget.EditText".equals(childNode.getClassName())) {
                    wxmsgEditText = childNode;
                    Log.e(TAG, "traverseNodeByDescription: wxmsgEditText");
                } else if (wxClassName.equals(WeChatTextWrapper.WechatClass.WECHAT_CLASS_CHATUI) && "android.widget.Button".equals(childNode.getClassName()) && getResources().getString(R.string.send).equals(childNode.getText())) {
                    sendMsgBtn = childNode;
                    sendBtnCoord = getNodeInfoCoordinate(childNode);
                    Log.e(TAG, "traverseNodeByDescription: sendBtnCoord[0]=" + sendBtnCoord[0]);
                    Log.e(TAG, "traverseNodeByDescription: sendBtnCoord[1]=" + sendBtnCoord[1]);
                    if (execute) {
                        childNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        Log.d(TAG, "traverseNodeByDescription: sendMsgBtn.perftion(AccessibilityNodeInfo.ACTION_CLICK");
                    }
                } else if (wxClassName.equals(WeChatTextWrapper.WechatClass.WECHAT_CLASS_CHATUI) && "android.widget.ImageButton".equals(childNode.getClassName()) && childNode.getContentDescription().equals(getResources().getString(R.string.more_btn))) {
                    targets.add(childNode);
                } else if (wxClassName.equals(WeChatTextWrapper.WechatClass.WECHAT_CLASS_CHATUI) && "android.widget.TextView".equals(childNode.getClassName()) && getResources().getString(R.string.red_pack).equals(childNode.getText())) {
                    maps.put(getResources().getString(R.string.red_pack), childNode);
                }
                Log.d(TAG, "traverseNodeByDescription==: " + childNode.getText() + "  classname=" + childNode.getClassName().toString() + "  id=" + childNode.getViewIdResourceName() + "  des=" + childNode.getContentDescription());

//                childNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);
            }
//            childNode.recycle();
            traverseNodeByDescription(childNode, allNodes, execute);
        }
    }

    private boolean intputTargetName(AccessibilityNodeInfo node, List<AccessibilityNodeInfo> allNodes, String name) {
        allNodes.add(node);
        boolean result = false;
        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo childNode = node.getChild(i);
            if (null == childNode) {
                continue;
            }
            if ("android.widget.EditText".equals(childNode.getClassName())) {
                Log.d(TAG, "searchChinese: WechatUtils.FRIEND_NAME=" + name);
                result = setNodeText(childNode, name);
                WechatUtils.FRIEND_NAME = name;
                childNode.recycle();
            }
//            childNode.recycle();

//            Log.d(TAG, "searchChinese==: " + childNode.getText() + "  classname=" + childNode.getClassName() + "  id=" + childNode.getViewIdResourceName() + "  des=" + childNode.getContentDescription());
            if (result) {
                return true;
            }else{
                intputTargetName(childNode, allNodes, name);
            }

        }
        return false;
    }

    private static final String MONEY_TAG = "¥0.00";
    private static final String SEND_REDPACK_TAG = "塞钱进红包";

    private void traverseRedPackNode(AccessibilityNodeInfo node, List<AccessibilityNodeInfo> allNodes, String friendName) {
        allNodes.add(node);
        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo childNode = node.getChild(i);
            if (null == childNode) {
                continue;
            }
            if (childNode.getClassName().equals("android.widget.EditText")) {
                setNodeText(childNode, FeiLongService.feilongRespone.getMoney());
            }
            if (MONEY_TAG.equals(childNode.getText())) {
//                maps.put(MONEY_TAG,childNode);
            } else if (SEND_REDPACK_TAG.equals(childNode.getText())) {
                sendRedPackNode = childNode;
                handler.sendEmptyMessageDelayed(SEND_RED_PACK, 300);
//                maps.put(SEND_REDPACK_TAG,childNode);
            }
            Log.e(TAG, "traverseRedPackNode:text " + childNode.getText() + "  classname=" + childNode.getClassName() + "  id=" + childNode.getViewIdResourceName() + "  des=" + childNode.getContentDescription());
            traverseRedPackNode(childNode, allNodes, friendName);
//            childNode.recycle();
        }
    }

    private void traverseNode(AccessibilityNodeInfo node, List<AccessibilityNodeInfo> allNodes, String friendName) {
        allNodes.add(node);
        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo childNode = node.getChild(i);
            if (null == childNode ) {
                continue;
            }
            Log.e(TAG, "traverseNode:text " + childNode.getText() + "  classname=" + childNode.getClassName() + "  id=" + childNode.getViewIdResourceName() + "  des=" + childNode.getContentDescription());
//            if (childNode.getText().toString().contains(getString(R.string.contain))) {
//                return;
//            }
//            if (childNode.getText().toString().contains(getString(R.string.search_internet_result))) {
//                return;
//            }
            wxfriendresearchs.add(childNode);
            traverseNode(childNode, allNodes, friendName);
//            childNode.recycle();
        }
    }

    private AccessibilityNodeInfo allowNodeInfo;

    private void traverseNodeByText(AccessibilityNodeInfo node, List<AccessibilityNodeInfo> allNodes, String text) {
        List<AccessibilityNodeInfo> list = new ArrayList<>();
        allNodes.add(node);
        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo childNode = node.getChild(i);
            if (null == childNode) {
                continue;
            }
            Log.d(TAG, "traverseNodeByText text: " + childNode.getText() + "  classname=" + childNode.getClassName().toString() + "  id=" + childNode.getViewIdResourceName() + "  getContentDescription=" + childNode.getContentDescription());
            if (null != childNode.getText()) {
                if (childNode.getText().toString().contains(text)) {
                    targets.add(childNode);
                }
                if ("确定".equals(childNode.getText().toString())) {
                    allowNodeInfo = childNode;
                }
            }
            traverseNodeByText(childNode, allNodes, text);
//            childNode.recycle();
        }
    }

    private AccessibilityNodeInfo taobaoSearchEdit;
    private AccessibilityNodeInfo taobaoSearchBtn;
    public static String searchKey;

    private void traverseTaoBaoNode(AccessibilityNodeInfo node, List<AccessibilityNodeInfo> allNodes, String text) {
        List<AccessibilityNodeInfo> list = new ArrayList<>();
        allNodes.add(node);
        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo childNode = node.getChild(i);
            if (null == childNode) {
                continue;
            }
            Log.d(TAG, "traverseNodeByText text: " + childNode.getText() + "  classname=" + childNode.getClassName().toString() + "  id=" + childNode.getViewIdResourceName() + "  getContentDescription=" + childNode.getContentDescription());
            if ("android.widget.EditText".equals(childNode.getClassName())) {
                setNodeText(childNode, searchKey);
            }
            if ("android.widget.Button".equals(childNode.getClassName()) && "搜索".equals(childNode.getText())) {
                taobaoSearchBtn = childNode;
            }

            traverseTaoBaoNode(childNode, allNodes, text);
//            childNode.recycle();
        }
    }

    private AccessibilityNodeInfo takePhotoNodeInfo;
    private AccessibilityNodeInfo meiyanNodeInfo;

    private void traverseCameraNode(AccessibilityNodeInfo node, List<AccessibilityNodeInfo> allNodes, String text) {
        List<AccessibilityNodeInfo> list = new ArrayList<>();
        allNodes.add(node);
        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo childNode = node.getChild(i);
            if (null == childNode) {
                continue;
            }
            Log.d(TAG, "traverseNodeByText text: " + childNode.getText() + "  classname=" + childNode.getClassName().toString() + "  id=" + childNode.getViewIdResourceName() + "  getContentDescription=" + childNode.getContentDescription());
            if ("android.widget.Button".equals(childNode.getClassName()) && "同意".equals(childNode.getText())) {
                childNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                return;
            }
            if ("android.widget.TextView".equals(childNode.getClassName()) && "拍照".equals(childNode.getText())) {
                takePhotoNodeInfo = childNode;
            }
            if ("android.widget.TextView".equals(childNode.getClassName()) && "美颜".equals(childNode.getText())) {
                meiyanNodeInfo = childNode;
            }

//             if ("android.widget.Button".equals(childNode.getClassName())&&"搜索".equals(childNode.getText())) {
//                 taobaoSearchBtn = childNode;
//            }

            traverseCameraNode(childNode, allNodes, text);
//            childNode.recycle();
        }
    }

    private void clickItemByText(AccessibilityNodeInfo node, List<AccessibilityNodeInfo> allNodes, String text) {
        List<AccessibilityNodeInfo> list = new ArrayList<>();
        allNodes.add(node);
        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo childNode = node.getChild(i);
            if (null == childNode) {
                continue;
            }
            if (null != childNode.getText() && childNode.getText().toString().contains(text)) {
                Log.e(TAG, "clickItemByText: " + text);
                childNode.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                return;
            }
            clickItemByText(childNode, allNodes, text);
//            childNode.recycle();
        }
    }

    private void traverseNodeByClass(AccessibilityNodeInfo node, List<AccessibilityNodeInfo> allNodes, String className) {
        List<AccessibilityNodeInfo> list = new ArrayList<>();
        allNodes.add(node);
        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo childNode = node.getChild(i);
            if (null == childNode) {
                continue;
            }
            Log.d(TAG, "traverseNodeByText text: " + childNode.getText() + "  classname=" + childNode.getClassName().toString() + "  id=" + childNode.getViewIdResourceName() + "  getContentDescription=" + childNode.getContentDescription());
            if (className.equals(childNode.getClassName().toString())) {
                Log.d(TAG, "traverseNodeByClassName: add+++++++++");
                targets.add(childNode);
            }
            traverseNodeByClass(childNode, allNodes, className);
//            childNode.recycle();
        }
    }

    public static final int CLOSE_TIP = 0;
    public static final int CLICK_EXE = 1;
    public static final int SEARCH_WXFRIEND = 2;
    public static final int FIND_RED_PACK = 3;
    public static final int SEND_RED_PACK = 4;
    public static final int CLICK_BACK = 5;
    public static final int CLICK_WEIXIN_SEND_MSG = 6;
    public static final int CLICK_WEIXIN_MAIN_TAB_CANTACT = 7;
    public static final int CLICK_WEIXIN_FRIEND = 8;
    public static final int CLICK_BACK_SERIES = 9;
    public static final int GO_HOME = 10;
    public static final int SEARCH_HANZI = 11;
    public static final int SEARCH_PINYIN = 12;
    public static final int SEARCH_FIRST_CHAR = 13;
    public static final int CHECK_SEARCH_RESULT = 14;//查询微信搜索结果
    public static final int SWIPE_UP = 15;
    private Handler handler = new Handler() {
        @SuppressLint("HandlerLeak")
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.e(TAG, "handleMessage: currentActivity=" + currentActivity);
            Log.e(TAG, "handleMessage: targetActivity=" + targetActivity);
            Log.e(TAG, "handleMessage: msg what=" + msg.what);
//            if (currentPackageName.equals(EXAGEAR_PKG)) {
            switch (msg.what) {
                case CLOSE_TIP:
                    click(0.1, 0.09, "关闭提示");
                    break;
                case CLICK_EXE:
                    created = true;
                    tap(134, 671);
//                    tap(260, 1050);//三防手机
                    exeFileIsStarted = true;
                    break;
                case SEARCH_WXFRIEND:
                    searchFriendList();
                    break;
                case CHECK_SEARCH_RESULT:
                    searchFriendList();
                    break;
                case SEARCH_PINYIN:
                    boolean searchResult = intputTargetName(rootNode, allNodes, feilongRespone.getTarget());
                    if (!searchResult) {
                        handler.sendEmptyMessageDelayed(SWIPE_UP, 2000);
                    }
                    break;
                case SEARCH_FIRST_CHAR:
                    boolean result = intputTargetName(rootNode, allNodes, feilongRespone.getTarget2());
                    if (!result) {
                        handler.sendEmptyMessageDelayed(SWIPE_UP, 2000);
                    }
                    break;
                case SWIPE_UP:
                    AppUtils.execCommand("adb shell input swipe 300 500 300 1200");
                    break;
                case FIND_RED_PACK:
                    click(0.161, 0.82, "找红包");
                    break;
                case CLICK_WEIXIN_SEND_MSG:
//                    click(0.1333, 0.945, "weixin");
                    traverseNodeByDescription(rootNode, allNodes, true);
                    break;
                case CLICK_WEIXIN_MAIN_TAB_CANTACT:
                    click(0.383, 0.945, "CANTACT");
                    break;
                case CLICK_WEIXIN_FRIEND:
                    tap(200, 280);
                    break;
                case SEND_RED_PACK:
                    sendRedPackNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    weixinType = -1;
                    break;
                case GO_HOME:
                    AppUtils.goHome(AewmeService.this);
                case CLICK_BACK:
                    performGlobalAction(GLOBAL_ACTION_BACK);
                case CLICK_BACK_SERIES:
                    if (null == currentActivity) {
                        performGlobalAction(GLOBAL_ACTION_BACK);
                    } else {
                        if (currentActivity.equals(targetActivity)) {
                            Log.d(TAG, "handleMessage:currentActivity= " + currentActivity + " targetActivity= " + targetActivity);
                            handler.removeMessages(CLICK_BACK_SERIES);
                            if (WeChatTextWrapper.WechatClass.WECHAT_CLASS_LAUNCHUI.equals(targetActivity)) {
                                EventBus.getDefault().post(new WechatHomeFinish());
                            }
                            targetActivity = "";
                        } else {
                            performGlobalAction(GLOBAL_ACTION_BACK);
                            handler.sendEmptyMessageDelayed(CLICK_BACK_SERIES, 1000);
                        }
                    }
                    break;

            }
        }
    };

    private void toWechatFirstUI() {
        Log.e(TAG, "toWechatFirstUI: ");
        targetActivity = WeChatTextWrapper.WechatClass.WECHAT_CLASS_LAUNCHUI;
        handler.sendEmptyMessageDelayed(CLICK_BACK_SERIES, 300);
    }

    /**
     * 回到微信主页
     *
     * @param weixinMsg
     * @throws RemoteException
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(WechatHome weixinMsg) throws RemoteException {
        targetActivity = WeChatTextWrapper.WechatClass.WECHAT_CLASS_LAUNCHUI;
        handler.sendEmptyMessageDelayed(CLICK_BACK_SERIES, 500);
    }

    /**
     * 处理微信指令
     *
     * @param weixinMsg
     * @throws RemoteException
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(WeixinMsg weixinMsg) throws RemoteException {
        Log.d(TAG, "onEventMainThread: weixinMsg=" + weixinMsg);
        if (WeChatTextWrapper.WechatClass.WECHAT_CLASS_CHATUI.equals(currentActivity) && weixinMsg.getType() == WEIXIN_MSG) {
            sendWxmsg(weixinMsg.getMessage());
        } else {
            if (WeChatTextWrapper.WechatClass.WECHAT_CLASS_LAUNCHUI.equals(currentActivity)) {
                handler.sendEmptyMessageDelayed(CLICK_WEIXIN_SEND_MSG, 100);
                handler.sendEmptyMessageDelayed(CLICK_WEIXIN_MAIN_TAB_CANTACT, 200);
            } else {
                toWechatFirstUI();
            }
        }
        if (1 == 1) return;
        switch (currentActivity) {
            case WeChatTextWrapper.WechatClass.WECHAT_CLASS_CHATUI:
                if (weixinMsg.getType() == WEIXIN_FIND_NAME) {
                    if (!weixinMsg.getMessage().equals(lastUserName)) {
                        performGlobalAction(GLOBAL_ACTION_BACK);
                        handler.sendEmptyMessageDelayed(CLICK_BACK, 100);
                    }
                } else if (weixinMsg.getType() == WEIXIN_MSG) {
                    Log.d(TAG, "onEventMainThread: wxmsgEditText=" + wxmsgEditText);
                    sendWxmsg(weixinMsg.getMessage());
                }

                break;
            case WeChatTextWrapper.WechatClass.WECHAT_CLASS_LAUNCHUI:
                Log.e(TAG, "onEventMainThread: searchBtn=" + searchBtn);
//                if (null == searchBtn) {
//                } else {
//                    searchBtn.performAction(AccessibilityNodeInfo.ACTION_CLICK);
//                }

                break;
            case WeChatTextWrapper.WechatClass.WECHAT_CLASS_MAINSEARCH:
//                Log.d(TAG, "onEventMainThread: searchEditText=" + searchFriendEditText);
//                if (null == searchFriendEditText) {
                performGlobalAction(GLOBAL_ACTION_BACK);
                Log.e(TAG, "onEventMainThread: GLOBAL_ACTION_BACK");
//                } else {
//                    setNodeText(searchFriendEditText, WechatUtils.FRIEND_NAME);
//                }
                break;
            default:
                performGlobalAction(GLOBAL_ACTION_BACK);
                break;
        }
    }

    //
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void searchFriendList() {
        Log.e(TAG, "searchFriendList===: ");
        traverseNode(rootNode, allNodes, WechatUtils.FRIEND_NAME);
        Log.d(TAG, "wxfriendresearchs: " + wxfriendresearchs.size());
        if (wxfriendresearchs.size() > 0) {
            int index = -1;
            for (int i = 0; i < wxfriendresearchs.size(); i++) {
                AccessibilityNodeInfo info = wxfriendresearchs.get(i);
                if (null != info.getText()) {
                    Log.d(TAG, "wxfriendresearchs: friend》联系人==" + info.getText() + " ===" + ("联系人".equals(info.getText().toString())));
//                    Log.e(TAG, "wxfriendresearchs: friend》最常使用==" + info.getText() + " ===" + ("最常使用".equals(info.getText().toString())));
                }
                if (null != info.getText() && (getString(R.string.contact).equals(info.getText().toString()))) {
                    index = i;
                    break;
                }
                if (null != info.getText() && (getString(R.string.recent_contact).equals(info.getText().toString()))) {
                    index = i;
                    break;
                }
            }
            if (index > 0) {
                if ("sendweixin".equals(FeiLongService.feilongRespone.getIntent())) {
                    weixinType = WEIXIN_MSG;
                } else if ("sendhongbao".equals(FeiLongService.feilongRespone.getIntent())) {
                    weixinType = WEIXIN_REDPKG;
                }
                handler.sendEmptyMessageDelayed(CLICK_WEIXIN_FRIEND, 500);
                handler.sendEmptyMessageDelayed(CLICK_WEIXIN_FRIEND, 3000);

                Log.e(TAG, "searchFriendList: " + wxfriendresearchs.size());
//                wxfriendresearchs.get(index + 1).performAction(AccessibilityNodeInfo.ACTION_CLICK);
//                                        nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);//选择好友
//                                        nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);//选择好友
            } else {
                findNext();
            }
        } else {
            findNext();
        }
    }

    private void findNext() {
        Log.d(TAG, "searchFriendList: WechatUtils.FRIEND_NAME =" + WechatUtils.FRIEND_NAME);
        if (WechatUtils.FRIEND_NAME.equals(feilongRespone.getTarget1())) {
            Log.d(TAG, "searchFriendList: SEARCH_PINYIN");
            handler.sendEmptyMessageDelayed(SEARCH_PINYIN, 500);
        } else if (WechatUtils.FRIEND_NAME.equals(feilongRespone.getTarget())) {
            Log.d(TAG, "searchFriendList: SEARCH_FIRST_CHAR");
            handler.sendEmptyMessageDelayed(SEARCH_FIRST_CHAR, 500);
        } else {
            Log.d(TAG, "ddsearchFriendList: " + FIND_FRIEND_COUNT);
            EventBus.getDefault().post(new TtsMsg("找不到联系人"));
            feilongRespone.setIntent("");
            weixinType = -1;
        }
    }

    public static int FIND_FRIEND_COUNT;

    private void handleFlow_LaunchUI() {
        Log.d(TAG, "handleFlow_LaunchUI: 通讯录find");
        try {
            //点击通讯录，跳转到通讯录页面
            WechatUtils.findTextAndClick(this, "通讯录");
            Thread.sleep(50);
            //再次点击通讯录，确保通讯录列表移动到了顶部
            WechatUtils.findTextAndClick(this, "通讯录");
            Thread.sleep(200);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void resetAndReturnApp() {
        hasSend = true;
        ActivityManager activtyManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = activtyManager.getRunningTasks(3);
        for (ActivityManager.RunningTaskInfo runningTaskInfo : runningTaskInfos) {
            if (this.getPackageName().equals(runningTaskInfo.topActivity.getPackageName())) {
//                activtyManager.moveTaskToFront(runningTaskInfo.id, ActivityManager.MOVE_TASK_WITH_HOME);
                return;
            }
        }
    }

    /**
     * Check 当前辅助服务是否启用
     *
     * @param serviceName
     * @return
     */
    public boolean checkAccessibilityEnabled(String serviceName) {
        Log.d(TAG, "checkAccessibilityEnabled: " + mAccessibilityManager);
        if (null == mAccessibilityManager) {
            return false;
        }
        List<AccessibilityServiceInfo> enabledAccessibilityServiceList = mAccessibilityManager.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_GENERIC);
        for (AccessibilityServiceInfo info : enabledAccessibilityServiceList) {
            Log.i(TAG, "checkAccessibilityEnabled: 111" + info.getId());
            if (info.getId().contains("com.feilong.edgeAI")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 前往开启辅助服务界面
     */
    public void goAccess() {
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

    /**
     * 模拟点击事件
     *
     * @param info
     */
    public void performViewClick(AccessibilityNodeInfo info) {
        if (info == null) {
            return;
        }
        while (info != null) {
            Log.d(TAG, "performViewClick:info.isClickable() " + info.isClickable());
            if (info.isClickable()) {
                Log.i(TAG, "performViewClick: " + info.getContentDescription());
                info.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                break;
            }
            info = info.getParent();
        }
    }

    /**
     * 模拟返回操作
     */
    public void performBackClick() {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        performGlobalAction(GLOBAL_ACTION_BACK);
    }

    /**
     * 模拟下滑操作
     */
    public void performScrollBackward() {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        performGlobalAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
    }

    /**
     * 模拟上滑操作
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void performScrollForward() {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        performGlobalAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
    }

    /**
     * 查找对应文本的view
     *
     * @param text
     * @return
     */
    public AccessibilityNodeInfo findViewByText(String text, String className) {
        AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return null;
        }
        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(text);
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                if (nodeInfo != null) {
                    continue;
                }
                if (TextUtils.isEmpty(className)) {
                    return nodeInfo;
                } else {
                    if (className.equals(nodeInfo.getClassName())) {
                        return nodeInfo;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 查找对应文本的View
     *
     * @param text
     * @param clickable 该View是否可以点击
     * @return
     */
    public AccessibilityNodeInfo findViewByText(String text, boolean clickable) {
        AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return null;
        }
        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(text);
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                if (nodeInfo != null && (nodeInfo.isClickable() == clickable)) {
                    return nodeInfo;
                }
            }
        }
        return null;
    }

    /**
     * 查找对应ID的View
     *
     * @param id
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public AccessibilityNodeInfo findViewByID(String id) {
        AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return null;
        }
        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id);
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                if (nodeInfo != null) {
                    return nodeInfo;
                }
            }
        }
        return null;
    }

    /**
     * 自动点击对应文本的View
     *
     * @param text
     */
    public boolean clickTextViewByText(String text) {
        AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
        Log.d(TAG, "clickTextViewByText: " + accessibilityNodeInfo);
        if (accessibilityNodeInfo == null) {
            return false;
        }
        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(text);
        Log.d(TAG, "clickTextViewByText: nodeInfoList=" + nodeInfoList.size());
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                if (nodeInfo != null) {
                    performViewClick(nodeInfo);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 模拟点击对应ID的View
     *
     * @param id
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void clickTextViewByID(String id) {
        AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return;
        }
        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id);
        Log.d(TAG, "clickTextViewByID: nodeInfoList=" + nodeInfoList.size());
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                if (nodeInfo != null) {
                    performViewClick(nodeInfo);
                    break;
                }
            }
        }
    }

    /**
     * 模拟输入
     *
     * @param nodeInfo
     * @param text
     */
    public void inputText(AccessibilityNodeInfo nodeInfo, String text) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Bundle arguments = new Bundle();
            arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text);
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("label", text);
            clipboard.setPrimaryClip(clip);
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_PASTE);
        }
    }

    private void click(double x, double y, String description) {
        Log.d(TAG, "click: " + description);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            getScreen();
            tap((int) (screenWidth * x), (int) (screenHeight * y));
//                tap((int) (screenWidth * 0.2), (int) (screenHeight * 0.458));
        }
    }

    private boolean created;

    private void createContainer() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            created = true;
            getScreen();
            tap((int) (screenWidth * 0.943), (int) (screenHeight * 0.0727));
        }
    }

    @Override
    public void onInterrupt() {
        Log.d(TAG, "onInterrupt: ");

    }

    public void findItem(String name) {
        Log.d(TAG, "findItem: name=" + name);
        Log.d(TAG, "findItem: rootNode=" + rootNode);
        if (rootNode == null) {
            return;
        }
        List<AccessibilityNodeInfo> targetNodes = rootNode.findAccessibilityNodeInfosByText(name);
        Log.d(TAG, "onEventMainThread: rootNode=" + targetNodes.size());
        if (!targetNodes.isEmpty()) {
            for (AccessibilityNodeInfo targetNode : targetNodes) {
                Log.d(TAG, "onAccessibilityEvent: target=" + targetNode.getText());
                // 模拟点击操作（例如，模拟点击Button类型的节点）
                boolean bb = targetNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                Log.d(TAG, "onAccessibilityEvent: bb " + bb);
            }
        }
    }


    /**
     * 模拟点击事件
     *
     * @param x
     * @param y
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void tap(int x, int y) {
        Log.e(TAG, "模拟点击事件x=" + x + " y=" + y);

        GestureDescription.Builder builder = new GestureDescription.Builder();
        Path p = new Path();
        p.moveTo(x, y);
        builder.addStroke(new GestureDescription.StrokeDescription(p, 0L, 5L));
        GestureDescription gesture = builder.build();
        dispatchGesture(gesture, new GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                Log.e(TAG, "onCompleted: 完成..........");
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                Log.e(TAG, "onCompleted: 取消..........");
            }
        }, null);

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void swipeDown() {
        GestureDescription.Builder builder = new GestureDescription.Builder();

        // 模拟从屏幕中间向下滑动
        Path path = new Path();
        path.moveTo(0.5f, 0.5f);
        path.lineTo(0.5f, 0.1f);

        GestureDescription gesture = builder.addStroke(new GestureDescription.StrokeDescription(path, 0, 500)).build();
        dispatchGesture(gesture, null, null);
    }

    private void getScreen() {
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        screenWidth = display.getWidth();
        screenHeight = display.getHeight();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }

    public static void invokeEvent(Context context, String packageName) {
        AccessibilityManager accessibilityManager = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
        AccessibilityEvent event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
        event.setPackageName(packageName);
        accessibilityManager.sendAccessibilityEvent(event);
    }

    private void setNotications(AccessibilityEvent event) {
        Parcelable data = event.getParcelableData();
        if (data instanceof Notification) {
            Log.d("Tortuga", "Recieved notification");
            Notification notification = (Notification) data;
            if (notification.tickerText == null) return;
            String ticker = notification.tickerText.toString();
            String voice = ": [语音]";
            String type = "default";//微信消息类型
            if (ticker.contains(": [语音]")) {
                type = "voice";
            } else if (ticker.contains(": [位置]")) {
                type = "location";
            } else if (ticker.contains(": [图片]") || ticker.contains(": [相片]")) {
                type = "picture";
            } else if (ticker.contains(": [视频]") || ticker.contains(": [影片]")) {
                type = "video";
            } else if (ticker.contains(": [文件]") || ticker.contains(": [位置]")) {
                type = "file";
            } else if (ticker.contains(": [微信红包]")) {
                type = "redpacket";
            } else if (ticker.contains(": [转账]") || ticker.contains(": [轉賬]")) {
                type = "transfer";
            } else if (ticker.contains(": [个人名片]") || ticker.contains("向你推薦了")) {
                type = "card";
            } else if (ticker.contains(": [聊天记录]") || ticker.contains(": [聊天記錄]")) {
                type = "history";
            } else if (ticker.contains(": [动画表情]") || ticker.contains(": [動態貼圖]")) {
                type = "expression";
            } else if (ticker.contains(": [笔记]") || ticker.contains(": [筆記]")) {
                type = "note";
            } else if (ticker.contains(": [卡包]") || ticker.contains(": [卡券]")) {
                type = "ticket";
            } else if (ticker.contains(": #接龙")) {
                type = "chains";
            } else if (ticker.contains(": http")) {
                type = "link";
            }
            if (ticker.contains(voice)) {
                ticker = ticker.substring(0, ticker.indexOf(voice) + voice.length());
            }
            if (!ticker.contains(":")) {
                return;
            }
            String text = ticker.replaceFirst(": \\[", "发来").replaceFirst(": ", "发来" + notications.get(event.getPackageName()) + "说").replaceAll(" ", "").replaceAll("\u202A", "");

            String[] arr = ticker.replaceAll("\u202A", "").split(":");
            Log.d(TAG, "onAccessibilityEvent: notications.get(event.getPackageName())=" + notications.get(event.getPackageName()));
            Log.d(TAG, "onAccessibilityEvent: ticker=" + ticker);
            Log.d(TAG, "onAccessibilityEvent: text==" + text);
            Log.d(TAG, "onAccessibilityEvent:arr0 " + arr[0]);
            if (MMS_PKG.equals(event.getPackageName()) && null != arr && arr.length > 0 && TextUtil.isNumeric(arr[0])) {
                return;
            }

            String tts = "收到" + text;
            if (event.getPackageName().equals(MMS_PKG)) {
                type = "text";
            }
            if (!text.isEmpty()) {
                NoticeMsg msg = new NoticeMsg(notications.get(event.getPackageName()), arr[0], arr[1], type);
                EventBus.getDefault().post(msg);
                Log.d(TAG, "setNotications: " + msg);
            }
        }
    }

    private int[] getNodeInfoCoordinate(AccessibilityNodeInfo nodeInfo) {
        if (nodeInfo != null) {
            // 这里假设已经找到了想要获取坐标的控件
            // 可以通过遍历、查找或筛选等方法定位到具体节点
            // ...

            // 获取控件的矩形区域信息
            Rect bounds = new Rect();
            nodeInfo.getBoundsInScreen(bounds);

            // 矩形区域信息包含了左上角和右下角坐标
            int left = bounds.left;
            int top = bounds.top;
            int right = bounds.right;
            int bottom = bounds.bottom;

            // 输出控件坐标信息
            Log.d(TAG, "Control Bounds: (" + left + ", " + top + ") - (" + right + ", " + bottom + ")");
            int[] arr = new int[]{(left + right) / 2, (top + bottom) / 2};
            return arr;
        }
        return null;
    }

    private int[] sendBtnCoord;
}
